package org.reborn.math

/**
 * A class representing a 3 dimensional polygon made up of
 * 3 or more points
 */
case class Polygon3F(val points:Seq[VectorF]){
  require(points.size >= 3)
  require(points.forall(_.length == 3))
  
  /**
   * Get the plane that the points of this polygon
   * lie on. All points are assumed to lie on the 
   * same plane. Plane normal direction is assumed to be
   * in counter-clock-wise direction based on the location
   * of the points
   */
  lazy val plane:Plane3F = calcPlane
  
  lazy val edges:Seq[Line3F] = calcLines
  
  private def calcPlane = {
    new Plane3F(points(0), ((points(0)-points(1)) cross (points(1)-points(2))).normalize)
  }
  
  private def calcLines = {
	val polyLines = new Array[Line3F](points.size)
	
	for(i <- 0 until polyLines.size-1){
	  polyLines(i) = new Line3F(points(i),points(i+1))
	}
	
	polyLines(polyLines.size-1) = new Line3F(points(polyLines.size-1),points(0))
	
	polyLines
  }
}

object Polygon3F{
  def apply(firstPoint:VectorF,points:VectorF*):Polygon3F = {
	val pointArray = new Array[VectorF](points.size + 1)
	for(i <- 0 until points.size)
	  pointArray(i+1) = points(i)
	
	pointArray(0) = firstPoint
    new Polygon3F(pointArray)
  }
}